package com.cjd.common.okhttp3

import android.content.Context
import android.text.TextUtils
import com.cjd.common.utils.MD5Util
import okhttp3.HttpUrl
import okhttp3.Request
import java.net.URLEncoder
import java.util.*

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/10/30
 * description
 */
interface IRequestParams {

    fun getRequest(context: Context, originRequest: Request): Request
}

class GetRequestParams(private val encryptType: String?, private val encryptKey: String?) :
    IRequestParams {
    override fun getRequest(context: Context, originRequest: Request): Request {

        val builder: HttpUrl.Builder = originRequest.url().newBuilder()

        if (TextUtils.equals(encryptType, "MD5")) {
            val paramsMap = TreeMap<String, String>()
            val time = "${System.currentTimeMillis() / 1000}"
            paramsMap["time"] = time

            val query = originRequest.url().uri().query
            if (!TextUtils.isEmpty(query)) {
                val paramsArray = query.split("&")
                for (str in paramsArray) {
                    val strArr = str.split("=")
                    val value = URLEncoder.encode(strArr[1], "UTF-8")
                    paramsMap[strArr[0]] = value
                }
            }

            if (paramsMap.isNotEmpty()) {

                val sign = md5AscEncrypt(paramsMap, encryptKey ?: "")

                builder.addQueryParameter("time", time).addQueryParameter("sign", sign)

                return originRequest.newBuilder().url(builder.build()).build()
            }
        }
        return originRequest
    }

    private fun md5AscEncrypt(map: TreeMap<String, String>, keyStr: String): String {
        val stringBuilder = StringBuffer()
        for ((key, value) in map) {
            stringBuilder.append(key)
            stringBuilder.append("=")
            stringBuilder.append(value)
            stringBuilder.append("&")
        }
        if (!TextUtils.isEmpty(keyStr))
            stringBuilder.append(keyStr)
        return MD5Util.encrypt2md5(stringBuilder.toString())
    }
}

class RequestParamsContext(
    val context: Context,
    val request: Request,
    var encryptType: String? = null,
    var encryptKey: String? = null,
    var iRequestParams: IRequestParams? = null
) {


    fun getInRequest(): Request {
        return when (request.method()) {
            "GET" -> {
                iRequestParams = GetRequestParams(encryptType, encryptKey)
                iRequestParams!!.getRequest(context, request)
            }
            else -> {
                request
            }
        }
    }
}